<template> 
  <div class="app-container">
    <el-form class="query-wrapper" :model="queryParams">
      <el-row>
    <el-select v-model="queryParams.vesselName" filterable clearable placeholder="Vessel" @change="selectVessel" style="width:180px"> 
      <el-option
        :key="item.vesselName"
        :label="item.vesselName"
        :value="item.vesselName"
        v-for="item in vessels"
      >
      </el-option>
    </el-select>
      &nbsp;&nbsp;
    <el-select v-model="queryParams.voyageNo" filterable clearable placeholder="Voyage" @change="selectVoyage"   style="width:100px">
      <el-option
        :key="item.voyageNo"
        :label="item.voyageNo"
        :value="item.voyageNo"
        v-for="item in voyages"
      >
      </el-option>
    </el-select>
    &nbsp;&nbsp;
    <el-select v-model="queryParams.pol" filterable clearable placeholder="POL">
      <el-option
        :key="item.fullPortName"
        :label="item.fullPortName"
        :value="item.fullPortName"
        v-for="item in pols"
      >
      </el-option>
    </el-select>
    &nbsp;&nbsp;
    <el-select v-model="queryParams.pod" filterable clearable allow-create placeholder="POD">
      <el-option
        :key="item.fullPortName"
        :label="item.fullPortName"
        :value="item.fullPortName"
        v-for="item in pods"
      >
      </el-option>
    </el-select>
    &nbsp;&nbsp; 
    <el-input v-model="queryParams.blNo" placeholder="B/L No" style="width:180px" clearable/>
        &nbsp;&nbsp;
    <el-button type="primary" icon="search" :loading="isLoading" @click="search">Search</el-button> 
    <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset>
  </el-row>
    </el-form>
    <div  v-loading="isLoading" body>
    <el-empty v-if="listData== null || listData.length === 0" description="No Data" :image-size="10" />
  
    <h3 style="text-align: center" v-if="listData!= null && listData.length > 0"><strong>CARGO MANIFEST</strong></h3>
    <div v-for="(item, index) in listData" :key="index" class="item-box" >
      <el-row class="manifest-tip-item__wrapper">
        <el-col :span="6" class="manifest-tip-item">
          <span class="title1"><strong>VESSEL NAME</strong></span>{{ item.vesselName }}
        </el-col>
        <el-col :span="8" class="manifest-tip-item">
          <span class="title"><strong>VOYAGE</strong></span>{{ item.voyageNo }}
        </el-col>
        <el-col :span="6" class="manifest-tip-item">
          <span class="title"><strong>FLAG</strong></span>{{ item.flagState }}
        </el-col>
        <el-col :span="4" class="manifest-tip-item">
          <span class="title2"><strong>IMO No.</strong></span>{{ item.imoNumber }}
        </el-col>
      </el-row>
      <el-row class="manifest-tip-item__wrapper">
        <el-col :span="6" class="manifest-tip-item">
          <span class="title1"><strong>PORT OF LOADING</strong></span>{{ item.pol }}
        </el-col>
        <el-col :span="8" class="manifest-tip-item">
          <span class="title"><strong>PORT OF DISCHARGING</strong></span>{{item.pod}}<span v-if="item.oldPod" style="font-size: 10px;vertical-align: text-top;">({{item.oldPod}})</span>
        </el-col>
        <el-col :span="6" class="manifest-tip-item">
          <span class="title"><strong>DATE OF DEPARTURE</strong></span>{{ item.atd }}
        </el-col>
        <el-col :span="4" class="manifest-tip-item">
          <span class="title2"><strong>N.R.T.</strong></span>{{ item.nrt }}
        </el-col>
      </el-row>
      <el-row class="manifest-tip-item__wrapper">
        <el-col :span="14" class="manifest-tip-item" style="padding-top: 0;"> 
            <!-- <el-button type="primary" :disabled="!singles[index]"  @click="editClickEvent(item,index)" v-hasPermi="['finalManifest:edit']">Edit</el-button> -->
          <el-button type="primary" @click="onMerge({ item, index })" v-hasPermi="['finalManifest:combine']">Combine</el-button>
			    <el-button type="warning" :disabled="!singles[index]"  @click="onSplitEvent(item)" >Split</el-button>		
			     <el-button type="primary" :disabled="!isMergedsingles[index]"  @click="onRollBakEvent(item)" >RollBack</el-button>		  
           &nbsp;
          <el-dropdown placement="bottom-start" v-if="listData.length != 0"  v-hasPermi="['draft:export']">
              <el-button type="warning" plain icon="download">
                Export<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item   fixed="right" @click="handleExport(item)"   v-hasPermi="['finalManifest:export']"> Manifest</el-dropdown-item>
                    <el-dropdown-item   fixed="right" :disabled="!singles[index]"  @click="pdfPreviewHandle('combineFileUrl')"> Combine</el-dropdown-item>
                    <el-dropdown-item   fixed="right" :disabled="!singles[index]"  @click="pdfPreviewHandle('splitFileUrl')"> Split </el-dropdown-item>
                    <el-dropdown-item   fixed="right" :disabled="!singles[index]"  @click="pdfPreviewHandle('correctionFileUrl')"> Correction</el-dropdown-item>
                </el-dropdown-menu>
                </template>
            </el-dropdown> 
		         &nbsp; 
          </el-col>
       </el-row> 
	  
      <el-table
        :ref="el => (tableRefs[index] = el)"
        stripe
        :data="item.details"
        class ="sj-table"
        :border="true"
        :cell-style="{textAlign:'center'}"
        show-overflow-tooltip
        @sort-change="handleSortChange" 
		    @row-dblclick="editClickEvent"  
       :span-method="splitSpanMethod"
	   	@selection-change="(selection) => handleSelectionChange(selection,item, index) " >
        <el-table-column type="selection" :selectable="selectable" width="40" fixed /> 
        <el-table-column prop="bookingNo" label="Booking No." width="105"  fixed /> 
        <el-table-column prop="blNo" label="B/L No." width="160"  fixed > 
		       <template  #default="scope"> 
			      <el-link  class="link-type" v-if="scope.row.id != null" @click="issueEvent(scope.row)"> {{ scope.row.blNo }}</el-link>
          </template>
		     </el-table-column> 
        <el-table-column prop="brand" label="Brand" width="150"/>         
        <el-table-column prop="marks" label="MARKS & NOS." width="120" show-overflow-tooltip/>
        <el-table-column prop="goodsDesc" label="DESCRIPTION OF GOODS" width="200" show-overflow-tooltip/>
        <el-table-column prop="totalUnits" label="NO.& KIND OF PKGS" width="160" >
          <template #header>
              NO.& KIND OF PKGS
          </template>
            <template #default="scope">
                <table width="100%"> <tbody><tr><td style="width:50%">{{ scope.row.totalUnits }}</td><td style="width:50%">{{ scope.row.unit }}</td></tr></tbody></table>
            </template>
        </el-table-column>
        <el-table-column  label="G/W(KGS)" prop="totalWeight" width="110"  /> 
        <el-table-column prop="totalVolume" label="MEASUREMENT(M³)" width="150" />
        <el-table-column prop="shipper" label="SHIPPER" width="250" />
        <el-table-column prop="consignee" label="CONSIGNEE" width="250" />
        <el-table-column prop="notifyParty" label="NOTIFY PARTY" width="250"  />
        <el-table-column prop="remark" label="REMARKS" width="120" /> 
        <el-table-column prop="masterReceipt" label="M/R" min-width="150"> 
             <!-- <el-button size="small" @click="handleUploadClick({ row: scope.row, type: 0, accept: '.pdf' })"><el-icon><Upload /></el-icon></el-button>
            <template v-if="scope.row.masterReceipt">
              <div v-for="(item,index) in scope.row.masterReceipt.split(',')" :key="index">
                <el-link v-if="docTypeList.includes(item.split('.').pop())" href="javascript:void(0)" @click="pdfPreviewHandle(item)">{{ getFileName(item) }}</el-link>
                <img v-else class="final-img" :src="convertUrl(item)" @click="handleViewer({ imageList: [item], currentIndex: 0 })">
              </div>
            </template> -->
          <template #default="scope" > 
            <PreViewImageUpload v-if="scope.row.id != null" :record="scope.row" :isTable="false" isDelSub :isShowDel="false" :isPreview="true" :isBreakLine="true" :photos="scope.row.masterReceipt?scope.row.masterReceipt.split(','):[]" :url="uploadUrlMr" :id="scope.row.id" :limit="1" @onSuccess="submitUploadForm"  @onDelete="deleteFile({file:scope.row.masterReceipt,type:0,id:scope.row.id},()=>{},0)"/>
          </template>
        </el-table-column> 
		
        <el-table-column prop="" label="BL Final Draft" min-width="150">
          <template #default="scope">
            <template v-if="scope.row.id">
              <el-button size="small" @click="handleUploadClick({ row: scope.row, type: 5, accept: '.pdf' })"><el-icon><Upload /></el-icon></el-button>
              <template v-if="scope.row.blCopyFileUrl">
                <a href="javascript:void(0)" @click="pdfPreviewHandle(scope.row.blCopyFileUrl)">{{ getFileName(scope.row.blCopyFileUrl) }}</a>
              </template>
            </template>
          </template>
        </el-table-column>  
        <el-table-column prop="" label="REQUIRED B/L TYPE" min-width="150"> 
          <template #default="scope"  >    
            <el-select v-model="scope.row.blType" @change="handleBlRequired(scope.row)" v-if="scope.row.id != null" filterable clearable placeholder="Choose REQUIRED B/L TYPE">
              <el-option
                :key="index"
                :label="item"
                :value="index"
                v-for="(item,index) in blTypeList"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>  
		<!--
        <el-table-column prop="" label="Generate B/L" min-width="130" align="center" fixed="right"> 
          <template #default="scope"  >    
            <el-button class="btn-primary"  v-if="scope.row.id !=null"  @click="issueEvent(scope.row)"
              style="font-size:10px !important;">{{
              $t("ship.button.readyForIssue")
            }}</el-button>
          </template>
        </el-table-column> -->
		
        <el-table-column prop="loiTexFileUrl" label="LOI(TLX)" min-width="150"> 
          <template #default="scope"> 
            <div  v-if="scope.row.loiTexFileUrl" >
            <el-icon class="deletefile" @click="deleteFile({file:scope.row.loiTexFileUrl,type:1,id:scope.row.id})"><Delete /></el-icon>
              <el-link v-if="docTypeList.includes(scope.row.loiTexFileUrl.split('.').pop())" href="javascript:void(0)"  @click="pdfPreviewHandle(scope.row.loiTexFileUrl)">{{ getFileName(scope.row.loiTexFileUrl) }}</el-link>
              <img v-else class="final-img" :src="item" @click="handleViewer({ imageList: [scope.row.loiTexFileUrl], currentIndex: 0 })">               
            </div> 
          </template>
        </el-table-column> 
        <el-table-column prop="loiCleanFileUrl" label="LOI(CLEAN)" min-width="150"> 
          <template #default="scope"> 
            <div style="display: flex;">
              <div v-if="!scope.row.loiFileUrl&&scope.row.id">
              <el-button size="small"  @click="handleUploadClick({ row: scope.row, type: 2 })"><el-icon><Upload /></el-icon></el-button>
            </div>
            <div  v-if="scope.row.loiCleanFileUrl" >
			        <el-icon class="deletefile" @click="deleteFile({file:scope.row.loiCleanFileUrl,type:2,id:scope.row.id},function(){scope.row.loiCleanFileUrl=null})"><Delete /></el-icon>
			        <el-link v-if="docTypeList.includes(scope.row.loiCleanFileUrl.split('.').pop())" href="javascript:void(0)" @click="pdfPreviewHandle(scope.row.loiCleanFileUrl)">{{ getFileName(scope.row.loiCleanFileUrl) }}</el-link>
              <img v-else class="final-img" :src="item" @click="handleViewer({ imageList: [scope.row.loiCleanFileUrl], currentIndex: 0 })">
            </div>            
            </div>            
          </template>
        </el-table-column> 
        <el-table-column prop="vinFileUrl" label="VIN LIST" min-width="150"> 
          <template #default="scope"> 
            <div  v-if="scope.row.vinFileUrl" >
			        <el-icon class="deletefile" @click="deleteFile({file:scope.row.vinFileUrl,type:3,id:scope.row.id})"><Delete /></el-icon>
			        <el-link v-if="docTypeList.includes(scope.row.vinFileUrl.split('.').pop())" href="javascript:void(0)" @click="pdfPreviewHandle(scope.row.vinFileUrl)">{{ getFileName(scope.row.vinFileUrl) }}</el-link>
              <img v-else class="final-img" :src="item" @click="handleViewer({ imageList: [scope.row.vinFileUrl], currentIndex: 0 })">
            </div> 
            <div v-if="!scope.row.vinFileUrl && scope.row.id">
              <el-button size="small" @click="handleUploadClick({ row: scope.row, type: 3 })"><el-icon><Upload /></el-icon></el-button>
            </div>
          </template>
        </el-table-column> 
        <el-table-column prop="blStatus" label="B/L Status" width="120"/>  
      </el-table>
    </div>
  </div>
    <el-dialog  :width="800" destroy-on-close draggable :title="dialogTitle" v-model="dialogFormVisible">
      <el-form :model="formParam" :rules="rules" label-width="180px"  ref="custForm">          
        <el-row>
          <el-col :span="12">
            <el-form-item label="MARKS & NOS." prop="marks" required>
              <el-input   v-model="formParam.marks"></el-input>
            </el-form-item>
          </el-col> 
          <el-col :span="12">
            <el-form-item label="DESCRIPTION OF GOODS" prop="goodsDesc" required>
              <el-input  v-model="formParam.goodsDesc"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="12">
            <el-form-item label="NO.& KIND OF PKGS" prop="totalUnits" required>
              <el-input-number v-model="formParam.totalUnits" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="MEASUREMENT(M³)" prop="totalVolume" required>
              <el-input-number v-model="formParam.totalVolume" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="G/W(KGS)" prop="totalWeight" required>
              <el-input-number v-model="formParam.totalWeight" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Unit" prop="unit" required>
              <el-select v-model="formParam.unit" allow-create filterable >
                <el-option v-for="item in units" :key="item" :value="item" :index="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="SHIPPER" prop="shipper">
          <el-input type="textarea" v-model="formParam.shipper"></el-input>
        </el-form-item>
        <el-form-item label="CONSIGNEE" prop="consignee">
          <el-input type="textarea" v-model="formParam.consignee"></el-input>
        </el-form-item>
        <el-form-item label="NOTIFY PARTY" prop="notifyParty" required>
          <el-input type="textarea"   v-model="formParam.notifyParty"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="16">
            <el-form-item label="REMARKS" prop="remark">
              <el-input v-model="formParam.remark"/> 
            </el-form-item>
          </el-col> 
          <el-col :span="8">
            <el-form-item label="B/L Status" prop="blStatus" :label-width="110">
             <el-select v-model="formParam.blStatus" filterable clearable> 
               <el-option v-for="item in statuss" :key="item" :label="item" :value="item" />
             </el-select>
        </el-form-item>
          </el-col>
        </el-row> 
        
        <el-form-item label="Update LOI" prop="correctionFileUrl">
          <el-button onclick="this.nextSibling.click()"  v-hasPermi="['finalManifest:upload']"> {{ $t("ship.button.upload") }}</el-button>
          <input type="file" id="upload-file" v-show="false"  @change="uploadFile($event)" accept=".pdf,.jpg,.png" />
          <a href="javascript:void(0)" @click="downloadPDF(formParam.correctionFileUrl)">{{formParam.fileName?formParam.fileName: getFileName(formParam.correctionFileUrl) }}</a>
        </el-form-item>
        
      </el-form> 
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">{{ $t("ship.button.cancel") }}</el-button> 
          <el-button type="primary" @click="submitForm">{{ $t("ship.button.submit") }}</el-button>
        </span>
      </template>
    </el-dialog>
    <input type="file" id="upload-file-loi"  ref="uploadFileInput"  @change="uploadFileLoi($event)" :accept="inputAccept" style="display: none;" />
    <el-image-viewer v-if="imageViewParams.viewerVisible" :url-list="imageViewParams.imageList" :initial-index="imageViewParams.currentIndex" @close="imageViewParams.viewerVisible = false" />
    <MergeModal ref="mergeModal" @success="onSuceess" />
    <SplitModal ref="splitModal" @success="onSuceess" />
    <FileUpload ref="fileUploadRef" :isDownTemplate="false" :isAlink="false" :uploadData="uploadData"  :uploadFileUrl="uploadFileUrl" :fileType="fileType" @update:modelValue="updateFileUpload"  />
  </div>
</template>
<script lang="ts" setup name="finalManifest">
// @ts-nocheck
import { ref, onMounted, reactive, toRef, nextTick } from "vue";
import { downloadFile } from "@/utils/downloadFile";
import {hasTableEditAuth} from "@/utils/auth";
import service from "@/utils/request";
import { hasAuth } from "@/utils/auth";
import { useMixinAuth } from "@/components/mixin/auth.js";
import testauth from "@/plugins/auth.js";
 
import { ElNotification, ElMessageBox, ElMessage } from "element-plus";
import {convertUrl} from "@/utils/tencentCos";
import SplitModal from "./modules/SplitModal.vue";
import MergeModal from './modules/MergeModal.vue';
import { useTablesDrag } from '@/hooks/useHooks' 
import { routeLocationKey } from "vue-router";
import PreViewImageUpload from '@/components/ImageUpload/PreViewImageUpload.vue' 
const route = useRoute();
const router = useRouter(); 
const uploadUrl='/shipping/cargoManifest/uploadVoucher' 
const uploadUrl2='/shipping/cargoManifest/uploadVoucher' 
const uploadUrlMr='/shipping/cargoManifest/uploadMr'
const docTypeList = ['pdf', 'xlsx', 'xls', 'docx', 'doc']
const accept = '.pdf'
const { tableRefs, proxy, initTableDrag } = useTablesDrag();
const units = ["BOXES", "CARTONS", "UNITS", "SKIDS", "PALLETS"]
const blTypeList=['Original B/L','Telex Release B/L','Memo B/L','Seaway B/L']
let brands = reactive([])
const multiples = ref({})
const singles = ref({})
 
onMounted( async() => { 
  let result = await service.get("/shipping/schedule/getAllSchedule");
  if (result) {
    vessels.value = result.data;
  }
  result = await service.get("/shipping/brand/list");
  if(result){
    brands = result.data
  }
  refreshTable();
});


const blTypeListFilter = (value) => {
  return blTypeList[value]
}
let vessels = ref([] as any);
let voyages = ref([] as any);
let pols = ref([] as any);
let pods = ref([] as any);
const statuss = ["Released","Draft Verification","Waiting For Draft"]

const handleExport = (item) => {
  downloadFile("/shipping/cargoManifest/export/"+item.id, queryParams, `Export for POD Agency.xlsx`);
}

const handleExportCombine = (item) => {
	downloadFile(item.combineFileUrl);
}

// 请求搜索下来条件
const getVoyageList = async () => {
  const { data } = await service.get("/shipping/voyage/list", {
    params: { status: 0 }
  });
  if (data) {
    voyages.value = data;
  }
};

const total = ref(0);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  voyageNo: null,
  status: 0,
  type: 1,
  orderByColumn: undefined,
  isAsc: undefined
});


const listData = ref([ ] as any);

// 搜索列表
const refreshTable =  async() => {
  window.localStorage.setItem("voyageNo",queryParams.voyageNo);
  window.localStorage.setItem("vesselName",queryParams.vesselName);
  // clear previous data immediately to avoid showing stale results while fetching
  listData.value = [];
  total.value = 0;
  isLoading.value = true;

  service.get("/shipping/cargoManifest/getTable", {
    params: queryParams
  }).then(result=>{
    listData.value = result.data;
    total.value = result.total; 
    initTableDrag();
  }).catch(error => {
    console.log(error)
  }).finally(() => {
    isLoading.value = false;
  })
};
const resetQuery = (data) => {
    Object.assign(queryParams, data)
    listData.value = []
    total.value = 0
}
const custForm = ref(null);
const dialogTitle = ref("");
const initForm = {
  id: null,
  blNo: null,
  brand: null,
  notifyParty: null,
  totalWeight: null,
  totalUnits: null,
  totalVolume: null,
  shipper: null,
  consignee: null,
  unit:null,
  marks: null,
  blStatus:null,
  blType: null,
  goodsDesc: null,
  remark: null,
  correctionFileUrl:null,
  fileName:null
};

const formParam = reactive(Object.assign({}, initForm));
let dialogFormVisible = ref(false);

const editClickEvent = (row:any) => { 
 if(row.id != null && hasTableEditAuth("finalManifest:edit")){
   dialogTitle.value = "Update Manifest";
   dialogFormVisible.value = true;
   Object.keys(initForm).forEach(k => (formParam[k] = row[k]));
   isAdd = false;
 } 
};

let isAdd = false;
const pageQuery = async e => {
  queryParams.pageNum = e.page;
  queryParams.pageSize = e.limit;
  refreshTable();
};
const isLoading = ref(false);

const search = () => { 
  if(queryParams.voyageNo == null){
    ElMessage({
      message: "Please Select Vessel and Voyage to query!",
      type: "warning"
    });
    return;
  }
  refreshTable();
};

const handleBrand = (row)=>{
  ElMessageBox.confirm("Confirm to set Brand?", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel",
  }).then(async () => {
     await service.put(`shipping/cargoManifest/`,row)
     ElNotification.success({
      title: "Prompt information",
      message: "close manifest success!",
      position: "bottom-right"
    });
    refreshTable()
  })
}

async function deleteFile(data,callback,type) {   
  if(type==0){
    if(data) {
		   await service["delete"]("/shipping/cargoManifest/deleteFile?id="+data.id+"&type="+data.type+"&file="+data.file);
		   ElNotification.success({ title: "Prompt information", message: "delete the File success!", position: "bottom-right" });
       refreshTable();
	  } 
  }else{
    ElMessageBox.confirm("Confirm to Delete the file？", "Delete  Information", {
        type: "warning",
        confirmButtonText: "Confirm",
        cancelButtonText: "Cancel",
      }).then(async () => {
        if(data) {
          await service["delete"]("/shipping/cargoManifest/deleteFile?id="+data.id+"&type="+data.type+"&file="+data.file);
          ElNotification.success({ title: "Prompt information", message: "delete the File success!", position: "bottom-right" });
          refreshTable();
        } 
      });
  }
	
}  

const updateFileUpload= (data: any) => {
  refreshTable();
};

const generateUpdate=(row)=>{
  ElMessageBox.confirm("Whether to generate bill of lading?", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel",
  }).then(async () => {
    const params = {
    id: row.id,
    generateBl: row.generateBl||''
  };
    await service.put(`shipping/cargoManifest/updateStatus`,params)
     ElNotification.success({
      title: "Prompt information",
      message: "close manifest success!",
      position: "bottom-right"
    });
    refreshTable()
  })
}
// 上传issue
const uploadFileUrl=ref('shipping/cargoManifest/uploadLoi')
const fileType=ref(['.pdf'])
const fileUploadRef=ref(null)
const uploadData=ref({
  id:'',
  type:0,
})
const uploadFileForm=()=>{
proxy.$refs["fileUploadRef"].dialogUploadFileForm()
}
const handleSortChange = async (column: any) => {
  queryParams.orderByColumn = column.prop;
  queryParams.isAsc = column.order; //动态取值排序顺序
  refreshTable();
};

const resetForm = () => {
  //@ts-ignore
  custForm.value.resetFields();
};

const uploadFile=(event)=>{
  const urlFile = document.querySelector('#upload-file') 
  if(urlFile != null && urlFile.files != null &&  urlFile.files.length  > 0) {
    formParam.file=urlFile
    formParam.correctionFileUrl = URL.createObjectURL(urlFile.files[0]);
  formParam.fileName = urlFile.files[0].name;
  } 
}

// 当前记录行图片预览
let imageViewParams = ref({
  viewerVisible: false,
  imageList: [],
  currentIndex: 0
})

const handleViewer = ({ imageList = [], currentIndex = 0 }) => {
  imageViewParams.value = { viewerVisible: true, imageList, currentIndex }
}

// 当前记录行上传参数
let uploadParams = ref({
  row: {},
  type: null
})

let inputAccept = ref('')
// 添加ref引用
const uploadFileInput = ref(null)
const handleUploadClick = ({ row, type, accept = '.pdf,.jpg,.png' }) => {
  if(type==3||type==0){
    accept = '.pdf,.jpg,.png,.xlsx,.xls'
  }
  inputAccept.value = accept
  uploadParams.value = { row, type }
  // 使用ref直接访问元素
  uploadFileInput.value?.click()
}

const uploadFileLoi=(event)=>{
  const { row, type } = uploadParams.value
  const uploadUrl = '/shipping/cargoManifest/uploadLoi'
 const formData = new FormData()
  // 使用事件对象获取文件
  formData.append('file', event.target.files[0])
  formData.append('id', row.id)
  formData.append('type', type)
  service.post(uploadUrl, formData).then(res => {
     // 添加这行代码，重置文件输入框
    event.target.value = '';
    if (res.code === 0) {
      ElNotification.success({
        title: "Prompt information",
        message: "upload successful!",
        position: "bottom-right"
      });
      refreshTable();
    } else {
      ElNotification.error({
        title: "Prompt information",
        message: "upload failed!",
        position: "bottom-right"
      });
    }
  }).catch(error => {
    // 即使上传失败，也应该重置文件输入框
    event.target.value = '';
    console.error('Upload error:', error);
  });;
}

const submitForm = async () => { 
  const formData = new FormData()
  for (const [k, n] of Object.entries(formParam)) {
    if (k == 'file') {       
      continue
    }
    // @ts-ignore
    if(n != null)
    formData.append(k, n)
  }
  await service.post("shipping/cargoManifest/update", formData);
  // @ts-ignore
  ElNotification.success({
    title: "Prompt information",
    message: "save successful!",
    position: "bottom-right"
  });
  dialogFormVisible.value = false
  refreshTable();
};

// 并单操作
const selectable = (row: any) => {
  return row.blNo && row.blNo !== 'TOTAL:' && row.id
}
const onMerge = ({ item, index }) => {
  const selectableRows = toRef(tableRefs.value[index]).value.getSelectionRows()
  if (selectableRows.length < 2) {
    ElMessage({
      message: "Please select at least two items",
      type: "warning"
    });
    return;
  }
  const details = selectableRows.map(({ id, toalUnits,blNo }) => {
    return { id, toalUnits,blNo }
  })
  proxy.$refs['mergeModal'].onInit({ details })
}
const onSuceess = () => {
  refreshTable();
}

// 拆单操作
const onSplitEvent = (row: any) => {
  let item  =  selectList.value[0] 
  const totalUnits = Number(item.totalUnits)
  if (totalUnits >= 2) {
    proxy.$refs['splitModal'].onInit({ ...item, totalUnits });
  } else {
    ElMessage({
      message: "The number of units must be greater than 1",
      type: "warning"
    });
  }
}

const onRollBakEvent = (id)=>{
  let item  =  selectList.value[0]
   id=item.id
   ElMessageBox.confirm("CONFIRM ROLLBACK？", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel",
  }).then(async () => {
     await service.post(`shipping/cargoManifest/rollback/${id}`)
     ElNotification.success({
      title: "Prompt information",
      message: "Rollback Manifest Success!",
      position: "bottom-right"
    });
    refreshTable()
  })
}

const issueEvent = (row:any)=>{ 
  router.push({path:'/billOfLading/issueBL',query:{blNo:row.blNo}})
} 

const submitBlUploadForm = async (data) => { 
  let length= data.photos.length-1
  // @ts-ignore
  const params = {
    id: data.id,
    masterReceipt: data.photos[length]||' '
  };

  await service["put"]("/shipping/cargoManifest/updateMr", params);

  ElNotification.success({
    title: "Prompt information",
    message: "save successful!",
    position: "bottom-right"
  });
  refreshTable();
};

const splitIndex=ref(0)
const handleSplitRow = (scope: any, data: any, index: number) => { 
  const length=data.filter(item => item.blNo == scope.row.blNo).length; 
  splitIndex.value=index;
  if (length+1 > scope.row.totalUnits) {
    ElMessage({
      message: "Cannot be greater than Total Units",
      type: "warning"
    });
    return;
  }
  let itemIndex = data.findIndex(item => item.id == scope.row.id);
  listData.value[index].details[itemIndex].marks = scope.row.blNo +1;
  listData.value[index].details[itemIndex].totalUnits = scope.row.totalUnits -1;
  listData.value[index].details[itemIndex].isEdit = true;
  listData.value[index].details.splice(itemIndex + length, 0, {
    id: scope.row.id,
    blNo: scope.row.blNo,
    marks: scope.row.blNo +Number(length+1) ,
    goodsDesc: scope.row.goodsDesc,
    totalUnits: 1,
    totalWeight: scope.row.totalWeight,
    totalVolume: scope.row.totalVolume,
    shipper: scope.row.shipper,
    consignee: scope.row.consignee,
    notifyParty: scope.row.notifyParty,
    remark: scope.row.remark,
    isEdit:true
  });
};

interface SpanMethodProps {
  row: User;
  column: TableColumnCtx<User>;
  rowIndex: number;
  columnIndex: number;
}
// 拆单
const splitSpanMethod = ({ row, column, rowIndex, columnIndex }: SpanMethodProps) => {  
  if(splitIndex.value){
    if (columnIndex == 1||columnIndex==0) {
    const currentValue = row["blNo"];
    const preRow = listData.value[splitIndex.value].details[rowIndex - 1];
    const preValue = preRow ? preRow["blNo"] : null;
    if (currentValue === preValue) {
      // console.log('row', row)
      return { rowspan: 0, colspan: 0 };
    } else {
      // 否则计算当前单元格应该跨越多少行
      let rowspan = 1;
      for (let i = rowIndex + 1; i < listData.value[splitIndex.value].details.length; i++) {
        const nextRow = listData.value[splitIndex.value].details[i];
        const nextValue = nextRow["blNo"];
        if (nextValue === currentValue) {
          rowspan++;
        } else {
          break;
        }
      }
      return { rowspan, colspan: 1 };
    }
  }
  } 
};
 

const isMergedsingles = ref({})
const selectList=ref([])
const handleSelectionChange = (val,item,index) => { 
   selectList.value =val
  if(val.length==1){
	  singles.value[index] =  (val.length==1)
	  isMergedsingles.value[index] =  val[0].isMerged
  }
  
  multiples.value[index] = !val.length; 
}

const handleClose = async(row)=>{
  ElMessageBox.confirm("CONFIRM CLOSED？", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel",
  }).then(async () => {
     await service.put(`shipping/cargoManifest/close/`,row)
     ElNotification.success({
      title: "Prompt information",
      message: "close manifest success!",
      position: "bottom-right"
    });
    refreshTable()
  })
}

const selectVessel = async()=>{ 
  queryParams.voyageNo = null;
  queryParams.pol = null;
  queryParams.pod = null;
  voyages.value = [];
  pols.value = [];
  pods.value = [];
  // 清空已有数据，等待新的查询
  listData.value = [];
  total.value = 0;
  //@ts-ignore
  let item = vessels.value.find(n=>n.vesselName == queryParams.vesselName) 
  voyages.value = item.schedules
}

const selectVoyage = async()=>{
  queryParams.pol = null;
  queryParams.pod = null;
  // 清空已有数据，等待新的查询
  listData.value = [];
  total.value = 0;
   //@ts-ignore
  let item = voyages.value.find(n=>n.voyageNo == queryParams.voyageNo) 
  pols.value = item.pols
  pods.value = item.pods.filter(n => n.fullPortName)
}
  // 获取文件名称
  function getFileName(name) { 
    if(!name){
      return '';
    }
    // 如果是url那么取最后的名字 如果不是直接返回
    if (name.lastIndexOf("/") > -1) {
      return name.slice(name.lastIndexOf("/") + 1);
    } else {
      return name;
    }
  }

  
const handleBlRequired = (row)=>{
  ElMessageBox.confirm("Confirm to Set REQUIRED B/L TYPE?", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel",
  }).then(async () => {
    uploadData.value.id=row.id
    if(row.blType==1){
      uploadData.value.type=row.blType
      uploadFileForm()
    }else{
      await service.put(`shipping/cargoManifest/`,row)
      refreshTable()
    }
  })
}

  function downloadPDF(url) {
	  ElMessageBox.confirm("Confirm to Download the file？", "Download  Information", {
		type: "warning",
		confirmButtonText: "Confirm",
		cancelButtonText: "Cancel",
	  }).then(async () => {
            const newUrl = convertUrl(url);
			const a = document.createElement('a');
			a.href = newUrl;
			a.download = getFileName(url);
			a.click();

	  });
	}

  const pdfPreviewHandle = (name) => {
      let item  =  selectList.value[0]
      let url=item[name]
      const  pdfUrl=encodeURI(convertUrl(url))
      if(['pdf','docx','doc','xls','xlsx','txt'].some((item) => url.includes(item))){
        window.open(router.resolve({ path: '/pdfView/index', query: { pdfUrl: pdfUrl} }).href, '_blank')
      }else{
        downloadPDF(url)
      }
  }
const submitUploadForm = async (data) => { 
  let length= data.photos.length-1
  // @ts-ignore
  const params = {
    id: data.id,
    masterReceipt: data.photos[length]||' '
  };

  await service["put"]("/shipping/cargoManifest/updateMr", params);
  // // @ts-ignore
  ElNotification.success({
    title: "Prompt information",
    message: "save successful!",
    position: "bottom-right"
  });
  refreshTable();
};
  if(window.localStorage.getItem("callback")=="1" && window.localStorage.getItem("voyageNo")){
      window.localStorage.setItem("callback","2")
      queryParams.voyageNo=window.localStorage.getItem("voyageNo");
      queryParams.vesselName=window.localStorage.getItem("vesselName");
  }
  onMounted(async () => {
    if(queryParams.vesselName)
         refreshTable();
  });

</script>
<style lang="scss" scoped>
.manifest-tip-item__wrapper {
  padding-left: 16px;
  &:first-child {
    padding-top: 16px;
  }
  .manifest-tip-item {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    padding: 0 2px 16px 0;
    font-size: 13px;
    .title {
      display: inline-block; 
      width: 165px;
    }
    .title1 {
      display: inline-block;
      width: 130px;
    }
    .title2 {
      display: inline-block;
      width: 60px; 
    }
  }
}

div.el-dialog {
  width: 1100px !important;
  max-width: 95vw;

  .el-select {
    width: 100%;
  }

  element.style {
    width: 3000;
  }

  .el-icon-upload {
    font-size: 2rem;
    cursor: pointer;
  }
}
.final-img {
  width: 40px;
  height: 30px;
  margin-right: 5px;
  cursor: pointer;
  vertical-align: top;
  object-fit: cover;
}
.block {
  min-height: 100px;

  .el-row {
    margin: 10px 10px 20px;
  }
}
</style>